package com.example.application4.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import com.example.application4.R;
import com.example.application4.pojo.Diary;
import com.example.application4.util.SharedPreferencesManager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ListViewActivity extends AppCompatActivity {
    private ArrayList<HashMap<String, Object>> data; // 存储列表项的数据
    private String username; // 当前登录的用户名

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view); // 设置布局

        ListView list = findViewById(R.id.lvNetInfo); // 获取 ListView 控件
        username = getCurrentUsername(); // 获取当前用户名

        if (username == null) {
            Toast.makeText(this, "用户未登录或用户名称无效", Toast.LENGTH_SHORT).show(); // 提示用户未登录
            finish(); // 结束当前 Activity
            return;
        }

        setupListView(list); // 设置 ListView
        setupFloatingActionButton(); // 设置浮动按钮
    }

    private String getCurrentUsername() {
        SharedPreferences preferences = getSharedPreferences("appPreferences", MODE_PRIVATE); // 获取 SharedPreferences
        return preferences.getString("username", null); // 从 SharedPreferences 中读取用户名
    }

    private void setupListView(ListView list) {
        data = getData(); // 获取数据
        SimpleAdapter adapter = new SimpleAdapter(
                this, // 当前上下文
                data, // 数据源
                R.layout.listitem, // 列表项布局
                new String[]{"img", "title", "date"}, // 数据源中的键
                new int[]{R.id.img, R.id.title, R.id.date} // 列表项布局中的控件 ID
        );
        list.setAdapter(adapter); // 设置适配器

        list.setOnItemClickListener((parent, view, position, id) -> { // 设置点击事件
            HashMap<String, Object> item = (HashMap<String, Object>) parent.getItemAtPosition(position); // 获取点击的项
            setTitle(item.get("title").toString()); // 设置标题
            startActivity(new Intent(this, DiaryViewActivity.class).putExtra("id", (int) item.get("id"))); // 跳转到日记详情页
        });

        list.setOnItemLongClickListener((parent, view, position, id) -> { // 设置长按事件
            showContextMenu(parent, view, position, id); // 显示上下文菜单
            return true;
        });
    }

    private void setupFloatingActionButton() {
        FloatingActionButton menuButton = findViewById(R.id.menu_button); // 获取浮动按钮
        menuButton.setOnClickListener(this::showMenu); // 设置点击事件
    }

    private void showContextMenu(AdapterView<?> parent, View view, int position, long id) {
        PopupMenu menu = new PopupMenu(this, view); // 创建弹出菜单
        MenuInflater inflater = menu.getMenuInflater(); // 获取菜单填充器
        inflater.inflate(R.menu.context_menu, menu.getMenu()); // 填充菜单

        // 获取点击的项
        HashMap<String, Object> item = (HashMap<String, Object>) parent.getItemAtPosition(position);
        String title = item.get("title").toString();

        menu.setOnMenuItemClickListener(i -> { // 设置菜单项点击事件
            int itemId = i.getItemId();
            if (itemId == R.id.detail) {
                startActivity(new Intent(this, DiaryViewActivity.class)
                        .putExtra("id", (int) item.get("id"))); // 查看详情
            } else if (itemId == R.id.share) {
                Toast.makeText(this, "分享" + item.get("id"), Toast.LENGTH_SHORT).show();
            } else if (itemId == R.id.delete) {
                showDeleteDialog(view, parent, position); // 删除
            }
            return true;
        });

        menu.show();
    }

    private void showDeleteDialog(View view, AdapterView<?> parent, int position) {
        HashMap<String, Object> item = (HashMap<String, Object>) parent.getItemAtPosition(position);
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setIcon(R.drawable.tb_netease)
                .setTitle("确认删除" + item.get("title").toString() + "吗？")
                .setMessage("删除后将无法恢复，确认删除？")
                .setCancelable(true) // 设置是否可取消
                .setPositiveButton("确认", (dialog, which) -> { // 设置确认按钮
                    data.remove(position); // 移除数据
                    SharedPreferencesManager.removeDiaryEntry(this,username, (int) item.get("id"));
                    refreshListView(); // 刷新列表
                    Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss()); // 设置取消按钮
        builder.create().show(); // 显示对话框
    }

    private void showMenu(View view) {
        PopupMenu menu = new PopupMenu(this, view); // 创建弹出菜单
        MenuInflater menuInflater = menu.getMenuInflater(); // 获取菜单填充器
        menuInflater.inflate(R.menu.mymenu, menu.getMenu()); // 填充菜单

        menu.setOnMenuItemClickListener(item -> { // 设置菜单项点击事件
            if (item.getItemId() == R.id.add) {
                Intent intent = new Intent(this, AddDiaryActivity.class);
                someActivityResultLauncher.launch(intent); // 启动 Activity 并等待结果
            } else if (item.getItemId() == R.id.delete) {
                Toast.makeText(this, "删除", Toast.LENGTH_SHORT).show();
            }
            return true;
        });
        menu.setGravity(Gravity.END); // 设置菜单位置
        menu.show(); // 显示菜单
    }

    //处理返回结果的方法
    ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), // 注册 Activity 结果回调
            result -> {
                if (result.getResultCode() == RESULT_OK) {
                    handleActivityResult(result.getData()); // 处理结果
                }
            });

    private void handleActivityResult(Intent data) {
        if (data != null) {
            String title = data.getStringExtra("title");
            String info = data.getStringExtra("content");
            String date = data.getStringExtra("date");

            Diary diary = new Diary(0, title, info, date);
            SharedPreferencesManager.saveDiaryEntry(this, username, diary); //塞进用户sp
            addDiaryToList(diary); // 添加到列表
            Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
        }
    }

    private void addDiaryToList(Diary diary) {
        HashMap<String, Object> item = new HashMap<>();
        item.put("id", diary.getId());
        item.put("img", R.drawable.tb_netease);
        item.put("title", diary.getTitle());
        item.put("date", diary.getDate());
        data.add(item);
        refreshListView();
    }

    private void refreshListView() {
        ListView list = findViewById(R.id.lvNetInfo); // 获取 ListView 控件
        SimpleAdapter adapter = new SimpleAdapter(
                this, // 当前上下文
                data, // 数据源
                R.layout.listitem, // 列表项布局
                new String[]{"img", "title", "date"}, // 数据源中的键
                new int[]{R.id.img, R.id.title, R.id.date} // 列表项布局中的控件 ID
        );
        list.setAdapter(adapter); // 设置适配器
    }

    private ArrayList<HashMap<String, Object>> getData() {
        data = new ArrayList<>();
        List<Diary> diaryEntries = SharedPreferencesManager.getDiaryEntries(this, username);
        for (Diary diary : diaryEntries) {
            HashMap<String, Object> item = new HashMap<>();
            item.put("id", diary.getId());
            item.put("img", R.drawable.tb_netease);
            item.put("title", diary.getTitle());
            item.put("date", diary.getDate());
            data.add(item);
        }
        return data;
    }
}